package com.shujia;

/*
1.设计4个线程，其中两个线程每次对j增加1，另外两个线程对j每次减少1。
要求：使用内部类实现线程，对j增减的时候不考虑顺序问题。
 */
public class Exer3 {

    private int j;

    public static void main(String[] args) throws Exception {
        Exer3 exer3 = new Exer3();
        Object lock = new Object();
        for (int i = 0; i < 2; i++) {
            exer3.new Incr(lock).start();
            exer3.new Desc(lock).start();
        }

        Thread.sleep(2000);

        System.out.println(exer3.j);
    }


    class Incr extends Thread {
        Object lock;

        public Incr(Object lock) {
            this.lock = lock;
        }

        @Override
        public void run() {
            synchronized (lock) {
                for (int i = 0; i < 50000; i++) {
                    j++;
                }
            }


        }
    }

    class Desc extends Thread {
        Object lock;

        public Desc(Object lock) {
            this.lock = lock;
        }

        @Override
        public void run() {
            synchronized (lock) {
                for (int i = 0; i < 50000; i++) {
                    j--;
                }
            }

        }
    }


}
